<?php

namespace app\common\command\task;

use app\common\model\AppConfig;
use app\common\service\One23PanService;

/**
 * php think cron buildOne23PanSession
 */
class BuildOne23PanSession
{
    /**
     * invoke
     * @throws
     */
    public function invoke()
    {
        // 读取配置
        $appId = getAppId();
        $where = [
            ['app_id', '=', $appId],
            ['config_type', '=', 'one23Pan'],
            ['config_name', '=', 'clientSession'],
        ];
        $config = app(AppConfig::class)->where($where)->find();
        if (!$config) {
            return;
        }

        // 15天更新access_token
        if (time() - $config['update_time'] > 86400 * 10) {
            $this->execute($config);
        }
    }

    /**
     * execute
     * @throws
     */
    private function execute($config)
    {
        // 初始化服务
        $service = new One23PanService();
        $service->init($config['app_id']);

        // 获取access_token
        $service->initAccessToken();
        $accessToken = $service->getAccessToken();

        // 更新表
        $where = ['id' => $config['id']];
        app(AppConfig::class)->where($where)->update([
            'config_value' => $accessToken,
            'update_time' => time(),
        ]);
    }
}